import { login, getUserInfo, getUserDetailsById } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    state.token = data
    setToken(data)// token数据持久化
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }

}
const actions = {
  // 获取token
  async login(store, data) {
    const res = await login(data)
    store.commit('setToken', res)
  },
  // 获取用户信息
  async getUserInfo(store) {
    const res = await getUserInfo()
    const data = await getUserDetailsById(res.userId)
    store.commit('setUserInfo', { ...res, ...data })
  },
  // 删除token和userInfo
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    // 重置高权限退出后，权限的残留
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

